//外部使用


var bgColor = "#000000"; //背景
var bgColor2 = "#111111"; //黑色背景

// 白色背景下红涨绿跌
var upColor = "#F9293E"; //涨颜色红色
var downColor = "#01FFFF"; //跌颜色绿色

// 红涨蓝跌
var upColor2 = "#D70101"; //红色
var downColor2 = "#01FFFF"; //蓝色

// 黑色背景下红涨绿跌
var upColor3 = "#F9293E"; //红色
var downColor3 = "#83a791"; //绿色

// ma  颜色
var ma5Color = "#39afe6";
var ma10Color = "#da6ee8";
var ma20Color = "#ffab42";
var ma30Color = "#00940b";
// 坐标轴的颜色
var axisLineColor = '#9a9a9f';


// 黑色背景下  颜色
var ma5Color2 = "#9D9D9D";
var ma10Color2 = "#CECF00";
var ma20Color2 = "#CF01CF";
var ma30Color2 = "#038804";
// 坐标轴的颜色
var axisLineColor2 = '#4F0000';

var tabLineColor = '#FF0000';

/**
 * 15:20 时:分 格式时间增加num分钟
 * @param {Object} time 起始时间
 * @param {Object} num
 */
function addTimeStr(time, num) {
  var hour = time.split(':')[0];
  var mins = Number(time.split(':')[1]);
  var mins_un = parseInt((mins + num) / 60);
  var hour_un = parseInt((Number(hour) + mins_un) / 24);
  if (mins_un > 0) {
    if (hour_un > 0) {
      var tmpVal = ((Number(hour) + mins_un) % 24) + "";
      hour = tmpVal.length > 1 ? tmpVal : '0' + tmpVal; //判断是否是一位
    } else {
      var tmpVal = Number(hour) + mins_un + "";
      hour = tmpVal.length > 1 ? tmpVal : '0' + tmpVal;
    }
    var tmpMinsVal = ((mins + num) % 60) + "";
    mins = tmpMinsVal.length > 1 ? tmpMinsVal : 0 + tmpMinsVal; //分钟数为 取余60的数
  } else {
    var tmpMinsVal = mins + num + "";
    mins = tmpMinsVal.length > 1 ? tmpMinsVal : '0' + tmpMinsVal; //不大于整除60
  }
  return hour + ":" + mins;
}

//获取增加指定分钟数的 数组  如 09:30增加2分钟  结果为 ['09:31','09:32']
function getNextTime(startTime, endTIme, offset, resultArr) {
  var result = addTimeStr(startTime, offset);
  resultArr.push(result);
  if (result == endTIme) {
    return resultArr;
  } else {
    return getNextTime(result, endTIme, offset, resultArr);
  }
}


/**
 * 不同类型的股票的交易时间会不同
 * @param {Object} type   hs=沪深  us=美股  hk=港股
 */
var time_arr = function(type) {
  if (type.indexOf('us') != -1) { //生成美股时间段
    var timeArr = new Array();
    timeArr.push('09:30')
    return getNextTime('09:30', '16:00', 1, timeArr);
  } else if (type.indexOf('hs') != -1) { //生成沪深时间段
    var timeArr = new Array();
    timeArr.push('09:30');
    timeArr.concat(getNextTime('09:30', '11:29', 1, timeArr));
    timeArr.push('13:00');
    timeArr.concat(getNextTime('13:00', '15:00', 1, timeArr));
    return timeArr;
  } else if (type.indexOf('hk') != -1) { //生成港股时间段
    var timeArr = new Array();
    timeArr.push('09:30');
    timeArr.concat(getNextTime('09:30', '11:59', 1, timeArr));
    timeArr.push('13:00');
    timeArr.concat(getNextTime('13:00', '16:00', 1, timeArr));
    return timeArr;
  } else {
    return [];
  }

}


var get_m_data = function(m_data, type) {
  var priceArr = new Array();
  var avgPrice = new Array();
  var vol = new Array();
  var times = type == 'auto' ? [] : time_arr(type);
  var datalist = m_data[0];
  // console.log(datalist);
  for (let key in datalist) {
    priceArr.push(datalist[key][1]);

    avgPrice.push(datalist[key][2]);
    vol.push(datalist[key][3]);
    if (type == 'auto') {
      times[key] = datalist[key][0]
    }
  }
  return {
    priceArr: priceArr,
    avgPrice: avgPrice,
    vol: vol,
    times: times
  }
}



//==========================================分时表 option

/**
 * 生成分时option
 * @param {Object} m_data 分时数据
 * @param {Object} type 股票类型  us-美股  hs-沪深  hk-港股
 */
function initMOption(m_data, type) {
  let klinemax=500;
  if (m_data[0].length > 300 && m_data[0].length < 501) {
    klinemax = 500;
  }
  if (m_data[0].length > 200 && m_data[0].length < 301) {
    klinemax = 400;
  }
  if (m_data[0].length < 201) {
    klinemax = 300;
  }
  var m_datas = get_m_data(m_data, type);
  return {
    tooltip: { //弹框指示器
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params, ticket, callback) {
        var i = params[0].dataIndex;

        var color;
        if (m_datas.priceArr[i] > m_data.yestclose) {
          color = 'style="color:#ff4242"';
        } else {
          color = 'style="color:#26bf66"';
        }

        var html = '<div class="commColor" style="width:100px;"><div>当前价 <span  ' + color + ' >' + m_datas.priceArr[i] +
          '</span></div>';
        html += '<div>均价 <span  ' + color + ' >' + m_datas.avgPrice[i] + '</span></div>';
        html += '<div>涨跌 <span  ' + color + ' >' + ratioCalculate(m_datas.priceArr[i], m_data.yestclose) +
          '%</span></div>';
        html += '<div>成交量 <span  ' + color + ' >' + m_datas.vol[i] + '</span></div></div>'
        return html;
      }
    },
    axisPointer: {
      show: true
    },
    color: [ma5Color, ma10Color, ma20Color, ma30Color],
    grid: [{
      id: 'gd1',
      left: '0%',
      right: '1%',
      height: '70%', //主K线的高度,
      top: '2%'
    }, {
      left: '0%',
      right: '1%',
      top: '76.5%',
      height: '20%' //交易量图的高度
    }],
    xAxis:
      //==== x轴
      [{
          type: 'category',
          gridIndex: 0,
          data: m_datas.times,
          axisLabel: { //label文字设置
            show: true,
            color: axisLineColor,
          },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: {
              color: axisLineColor
            },
          },
          axisTick: {
            // 刻度
            show: false,
          },
          splitLine: {
            show: false,
          },
          splitNumber: klinemax,
          min: 'dataMin',
          max: klinemax
        },
        { //交易量图
          type: 'category',
          gridIndex: 1,
          data: m_datas.times,
          axisLabel: { //label文字设置
            color: axisLineColor,
            fontSize: 10
          },
          splitNumber: klinemax,
          min: 'dataMin',
          max: klinemax
        },
      ],
    yAxis:
      //y轴
      [{

          gridIndex: 0,
          scale: true,
          splitNumber: 3,
          position: 'right',
          axisLine: { //y轴显示
            show: false,
            onZero: false,
          },
          axisLabel: { //label文字设置
            inside: true, //label文字朝内对齐
            fontWeight: 'bold',
            color: function(val) {
              if (val == m_data.yestclose) {
                return '#aaa'
              }
              return val > m_data.yestclose ? upColor : downColor;
            }
          },
          axisTick: { //y轴刻度
            show: false,
          },
          splitLine: { //分割线设置
            show: true,
            lineStyle: {
              color: axisLineColor2,
              type: 'dashed'
            }
          },
        },
        { //交易图
          gridIndex: 1,
          splitNumber: 3,
          z: 4,
          axisLine: {
            onZero: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: { //label文字设置
            color: axisLineColor2,
            inside: true, //label文字朝内对齐
            fontSize: 8
          },
        }
      ],
    dataZoom: [{
      type: 'inside',
      xAxisIndex: [0, 1], //控件联动
      // start: 100,
      // end: 80,
    }],
    animation: false, //禁止动画效果
    backgroundColor: bgColor,
    blendMode: 'source-over',
    series: [{
        name: '当前价',
        type: 'line',
        data: m_datas.priceArr,
        smooth: true,
        symbol: "none", //中时有小圆点
        lineStyle: {
          normal: {
            opacity: 1,
            color: '#fff',
            width: 1
          }
        },
      },
      // {
      //   name: '涨跌',
      //   type: 'line',
      //   data: ratioCalculateline(m_datas.priceArr, m_data.yestclose),
      //   smooth: true,
      //   symbol: "none", //线条样式
      //   lineStyle: {
      //     normal: {
      //       opacity: 0.8,
      //       color: '#FFFF00',
      //       width: 1
      //     }
      //   },
      // },
      // areaStyle: {
      //   normal: {
      //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      //       offset: 0,
      //       color: 'rgba(255, 255, 255, 0.7)'
      //     }, {
      //       offset: 0.8,
      //       color: 'rgba(255, 255, 255, 0.02)'
      //     }], false),
      //     shadowColor: 'rgba(0, 0, 0, 0.1)',
      //     shadowBlur: 10
      //   }
      // },
      // {
      //   name: '均价',
      //   type: 'line',
      //   data: m_datas.avgPrice,
      //   smooth: true,
      //   symbol: "none", //中时有小圆点
      //   lineStyle: { //标线的样式
      //     normal: {
      //       opacity: 0.5,
      //       color: '#FFFF00',
      //       width: 1
      //     }
      //   }
      // },
      // {
      // 	type: 'line',
      // 	data: m_datas.priceArr,
      // 	smooth: true,
      // 	symbol: "none",
      // 	gridIndex: 1,
      // 	xAxisIndex: 1,
      // 	yAxisIndex: 1,
      // 	lineStyle: { //标线的样式
      // 		normal: {
      // 			width: 0
      // 		}
      // 	}
      // },
      {
        name: 'Volumn',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: m_datas.vol,
        barWidth: '1px',
        barMaxwidth: '1px',
        itemStyle: {
          normal: {
            // color: function(params) {
            // 	var colorList;
            // 	if (m_datas.priceArr[params.dataIndex] > m_datas.priceArr[params.dataIndex - 1]) {
            // 		colorList = upColor;
            // 	} else {
            // 		colorList = downColor;
            // 	}
            // 	return colorList;
            // },
            color: '#FFFF00'
          }
        }
      }
    ]
  };
}



/**
 * 计算价格涨跌幅百分比
 * @param {Object} price 当前价
 * @param {Object} yclose 昨收价
 */
function ratioCalculate(price, yclose) {
  return ((price - yclose) / yclose * 100).toFixed(3);
  // return ((price - yclose)).toFixed(0);
}

// 计算出涨跌幅度线数据
function ratioCalculateline(price, yclose) {
  let datas = [];
  for (let i = 0; i < price.length; i++) {
    datas[i] = ((price[i] - yclose)).toFixed(0);
  }
  // console.log(datas)
  return datas;
}






//数组处理
function splitData(rawData) {

  var datas = [];
  var times = [];
  var vols = [];
  for (var i = 0; i < rawData.length; i++) {
    datas.push(rawData[i]);
    times.push(rawData[i].splice(0, 1)[0]);
    vols.push(rawData[i][4]);
  }
  return {
    datas: datas,
    times: times,
    vols: vols
  };
}


//================================MA计算公式
function calculateMA(dayCount, data) {
  var result = [];
  if (data.datas[0][1].toString().split(".")[1] == undefined) {
    var tofix = 2;
  } else {
    var tofix = data.datas[0][1].toString().split(".")[1].length;
  }
  if (tofix == 1) {
    tofix = 2;
  }
  for (var i = 0, len = data.times.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    var sum = 0;
    for (var j = 0; j < dayCount; j++) {
      sum += data.datas[i - j][1];
    }
    result.push((sum / dayCount).toFixed(tofix));
  }
  return result;
}


//=================================================MADC计算公式

var calcEMA, calcDIF, calcDEA, calcMACD;

/*
 * 计算EMA指数平滑移动平均线，用于MACD
 * @param {number} n 时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcEMA = function(n, data, field) {
  var i, l, ema, a, tofix;
  a = 2 / (n + 1);
  if (field) {
    //二维数组
    ema = [data[0][field]];
    if (data[0][field].toString().split(".")[1] == undefined) {
      tofix = 2;
    } else {
      tofix = data[0][field].toString().split(".")[1].length;
    }
    if (tofix == 1) {
      tofix = 2;
    }
    for (i = 1, l = data.length; i < l; i++) {
      ema.push((a * data[i][field] + (1 - a) * ema[i - 1]).toFixed(tofix));
    }
  } else {
    //普通一维数组
    ema = [data[0]];
    for (i = 1, l = data.length; i < l; i++) {
      ema.push((a * data[i] + (1 - a) * ema[i - 1]).toFixed(3));
    }
  }
  return ema;
};

/*
 * 计算DIF快线，用于MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcDIF = function(short, long, data, field) {
  var i, l, dif, emaShort, emaLong;
  dif = [];
  emaShort = calcEMA(short, data, field);
  emaLong = calcEMA(long, data, field);
  if (data[0][1].toString().split(".")[1] == undefined) {
    var tofix = 2;
  } else {
    var tofix = data[0][1].toString().split(".")[1].length;
  }
  if (tofix == 1) {
    tofix = 2;
  }
  for (i = 0, l = data.length; i < l; i++) {
    dif.push((emaShort[i] - emaLong[i]).toFixed(tofix));
  }
  return dif;
};

/*
 * 计算DEA慢线，用于MACD
 * @param {number} mid 对dif的时间窗口
 * @param {array} dif 输入数据
 */
calcDEA = function(mid, dif) {
  return calcEMA(mid, dif);
};

/*
 * 计算MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {number} mid dea时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcMACD = function(short, long, mid, data, field) {
  var i, l, dif, dea, macd, result;
  result = {};
  macd = [];
  dif = calcDIF(short, long, data, field);
  dea = calcDEA(mid, dif);
  if (data[0][1].toString().split(".")[1] == undefined) {
    var tofix = 2;
  } else {
    var tofix = data[0][1].toString().split(".")[1].length;
  }
  if (tofix == 1) {
    tofix = 2;
  }
  for (i = 0, l = data.length; i < l; i++) {
    macd.push(((dif[i] - dea[i]) * 2).toFixed(tofix));
  }
  result.dif = dif;
  result.dea = dea;
  result.macd = macd;
  return result;
};


//=================================================MADC计算公式 end

//===============k线
function initKOption(cdata) {
  let startnum, endnum, klinemax;
  klinemax = cdata.length;
  if (cdata.length > 300 && cdata.length < 501) {
    startnum = 100, endnum = 80;
  }
  if (cdata.length > 100 && cdata.length < 301) {
    startnum = 100, endnum = 50;
  }
  if (cdata.length < 101) {
    startnum = 0, endnum = 100, klinemax = 100;
  }

  var data = splitData(cdata);

  var macd = calcMACD(12, 26, 9, data.datas, 1);

  return {
    tooltip: { //提示框组件
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      // formatter: function(data) {
      //   var htmllist = '<div>';
      //   htmllist += '时间:' + data[0].name + '<br/>';
      //   htmllist += '开盘价:' + data[0].value[1] + '<br/>';
      //   htmllist += '收盘价:' + data[0].value[2] + '<br/>';
      //   htmllist += '最低价:' + data[0].value[3] + '<br/>';
      //   htmllist += '最高价:' + data[0].value[4] + '<br/>';
      //   return htmllist;
      // }
    },
    color: [ma5Color2, ma10Color2, ma20Color2, ma30Color2],
    grid: [{
      id: 'gd1',
      left: '5px',
      right: '5px',
      height: '60%', //主K线的高度,
      top: '5%'
    }, {
      left: '5px',
      right: '5px',
      top: '68.5%',
      height: '10%' //交易量图的高度
    }, {
      left: '5px',
      right: '5px',
      top: '84%', //MACD 指标
      height: '12%'
    }],
    xAxis: [{ //主图
      type: 'category',
      data: data.times,
      scale: true,
      boundaryGap: true,
      axisLine: {
        show: true,
        onZero: false,
        lineStyle: {
          color: tabLineColor
        },
      },
      axisTick: {
        // 刻度
        show: false,
      },
      axisLabel: { //label文字设置
        color: axisLineColor,
        inside: false, //label文字朝外对齐
      },
      splitLine: { //分割线设置
        show: false,
        lineStyle: {
          color: axisLineColor2,
          type: 'dashed'
        }
      },
      splitNumber: klinemax,
      min: 'dataMin',
      max: klinemax
    }, { //交易量图
      type: 'category',
      gridIndex: 1,
      data: data.times,
      axisLabel: { //label文字设置
        color: axisLineColor,
        fontSize: 10
      },
      splitNumber: klinemax,
      min: 'dataMin',
      max: klinemax
    }, { //幅图
      type: 'category',
      gridIndex: 2,
      data: data.times,
      axisLabel: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: axisLineColor2
        },
      },
      splitNumber: klinemax,
      min: 'dataMin',
      max: klinemax
    }],

    yAxis: [{ //==主图
      show: true,
      scale: true,
      splitNumber: 4,
      position: 'left',
      axisLine: { //y轴显示
        show: false,
        onZero: false,
      },
      axisTick: { //y轴刻度
        show: false,
      },
      axisLabel: { //label文字设置
        show: false,
        color: axisLineColor,
        inside: true, //label文字朝内对齐
        lineStyle: {
          color: axisLineColor2
        }
      },
      splitLine: { //分割线设置
        show: true,
        lineStyle: {
          color: axisLineColor2,
          type: 'dashed'
        }
      },
    }, { //交易图
      gridIndex: 1,
      splitNumber: 3,
      z: 4,
      axisLine: {
        onZero: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisLabel: { //label文字设置
        color: axisLineColor,
        inside: true, //label文字朝内对齐
        fontSize: 8
      },
    }, { //幅图
      z: 4,
      gridIndex: 2,
      splitNumber: 4,
      axisLine: {
        onZero: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisLabel: { //label文字设置
        color: axisLineColor,
        inside: true, //label文字朝内对齐
        fontSize: 8
      },
    }],

    dataZoom: [{
      type: 'inside', // 模块 inside 或者 slide
      xAxisIndex: [0, 1, 2], //控件联动
      start: startnum,
      end: endnum,
      // rangeMode: ['value', 'percent']
    }],
    animation: true, //动画效果
    backgroundColor: bgColor,
    blendMode: 'source-over',
    series: [{
        // name: 'K线图',
        type: 'candlestick',
        data: data.datas,
        barWidth: '7px',
        barMaxwidth: '7px',
        large: true,
        largeThreshold: 300,
        
        itemStyle: {
          normal: {
            color: undefined,//upColor, //fd2e2e  ff4242
            color0: downColor,
            borderColor: upColor,//upColor3,
            borderColor0: undefined,
          }
        },
      }, {
        name: 'MA20',
        type: 'line',
        data: calculateMA(5, data),
        smooth: true,
        symbol: "none", //线条样式
        lineStyle: {
          normal: {
            opacity: 0.8,
            color: ma5Color2,
            width: 1
          }
        },
      },
      {
        name: 'MA50',
        type: 'line',
        data: calculateMA(10, data),
        smooth: true,
        symbol: "none",
        lineStyle: { //标线的样式
          normal: {
            opacity: 0.8,
            color: ma10Color2,
            width: 1
          }
        }
      },
      {
        name: 'MA60',
        type: 'line',
        data: calculateMA(20, data),
        smooth: true,
        symbol: "none",
        lineStyle: {
          opacity: 0.8,
          width: 1,
          color: ma20Color2
        }
      },
      {
        name: 'MA120',
        type: 'line',
        data: calculateMA(30, data),
        smooth: true,
        symbol: "none",
        lineStyle: {
          normal: {
            opacity: 0.8,
            width: 1,
            color: ma30Color2
          }
        }
      },
      {
        name: 'Volumn',
        type: 'bar',
        z: 4,
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: data.vols,
        barWidth: '7px',
        barMaxwidth: '7px',
        itemStyle: {
          normal: {
            color: function(params) {
              var color;
              if (data.datas[params.dataIndex][1] > data.datas[params.dataIndex][0]) {
                color = upColor;
              }else{
                color = downColor;
              }
              return color;
            },
            //borderColor: undefined ,
          }
        },
      },
      {
        name: 'MACD',
        type: 'bar',
        z: 4,
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.macd,
        barWidth: '1px',
        barMaxwidth: '1px',
        itemStyle: {
          normal: {
            color: function(params) {
              var colorList;
              if (params.data >= 0) {
                colorList = upColor3;
              } else {
                colorList = downColor3;
              }
              return colorList;
            },
          }
        },
      },
      {
        name: 'DIF',
        type: 'line',
        symbol: "none",
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.dif,
        lineStyle: {
          normal: {
            color: ma5Color2,
            width: 1
          }
        }
      },
      {
        name: 'DEA',
        type: 'line',
        symbol: "none",
        xAxisIndex: 2,
        yAxisIndex: 2,
        data: macd.dea,
        lineStyle: {
          normal: {
            opacity: 0.8,
            color: ma10Color2,
            width: 1
          }
        }
      }
    ]
  };

  

}
//  更新K线，不强制刷新K线
function updateKOption(data){
  data = splitData(data);
  var macd = calcMACD(12, 26, 9, data.datas, 1);
  return {
    xAxis:{
      data: data.times
    }
  };
}

export default {
  initMOption,
  initKOption,
  updateKOption,
  splitData,
  calcMACD
}
